package com.sales.service.impl;

import com.sales.dao.UserDao;
import com.sales.entity.User;
import com.sales.enums.ExceptionEnum;
import com.sales.excption.SalesException;
import com.sales.service.ProfileService;
import com.sales.service.UserService;
import com.sales.util.BCryptUtils;
import com.sales.util.UuidUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lihu on 2017/9/6.
 */
@Service
public class UserServiceImpl implements UserService, UserDetailsService {

    @Autowired
    UserDao userDao;

    @Autowired
    ProfileService profileService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.findByUsername(username);
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        if (StringUtils.isNotBlank(user.getRoles())) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(user.getRoles()));
        }
        return new org.springframework.security.core.userdetails.User(
                username, user.getPassword(), simpleGrantedAuthorities);
    }


    @Override
    @Transactional
    public void updatePws(String username, String pws) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            throw new SalesException(ExceptionEnum.USER_NOT_EXISTS);
        }
        user.setPassword(BCryptUtils.encrypt(pws));
        userDao.save(user);
    }

    @Override
    @Transactional
    public void createUser(String mobile, String username) {
        User user = userDao.findByUsername(mobile);
        if (user != null) {
            throw new SalesException(ExceptionEnum.USER_EXISTS);
        }
        user = new User(UuidUtil.getUuid(), mobile, BCryptUtils.encrypt("123456"), "ROLE_LOGIN");
        userDao.save(user);
        profileService.createProfile(mobile, username);
    }
}
